package com.htsk.city.services.wechat.service;


import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.util.WxMaConfigHolder;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.htsk.city.services.core.dao.WxUserDao;
import com.htsk.city.services.core.domain.WxUser;
import com.htsk.city.services.core.entity.R;
import com.htsk.city.services.wechat.vo.UserInfoVO;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
@Slf4j
public class WechatService {
    @Resource
    private WxMaService wxMaService;

    @Resource
    private WxUserDao wxUserDao;


    /**
     * 微信登录
     * @param code
     * @return
     */
    public R<String> wxLogin(String code){
        if (StrUtil.isBlank(code)) {
            return R.fail("empty code");
        }
        try {
            WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
            WxUser wxUser=wxUserDao.findByOpenId(session.getOpenid());
            if (wxUser==null){
                wxUser=new WxUser(session.getOpenid());
                wxUserDao.save(wxUser);
            }
            StpUtil.login(JSONUtil.toJsonStr(wxUser));
            return R.ok(StpUtil.getTokenValue());
        } catch (WxErrorException e) {
            log.error(e.getMessage(), e);
            return R.fail(e.getMessage());
        } finally {
            WxMaConfigHolder.remove();//清理ThreadLocal
        }
    }

    public R<UserInfoVO> getUserInfo(WxUser wxUser){
        WxUser user=wxUserDao.findByOpenId(wxUser.getOpenId());
        UserInfoVO userInfo=new UserInfoVO();
        userInfo.setNickname(userInfo.getNickname());
        userInfo.setAvatar(userInfo.getAvatar());
        return R.ok(userInfo);
    }

    public R<Boolean> saveUserInfo(WxUser wxUser,UserInfoVO userInfo){
        WxUser user=wxUserDao.findByOpenId(wxUser.getOpenId());
        user.setNickname(userInfo.getNickname());
        user.setAvatar(userInfo.getAvatar());
        user.setUpdateTime(DateUtil.date());
        wxUserDao.save(user);
        return R.ok(true);
    }
}
